import { defineStore } from 'pinia';
import { getLoginerInfo } from "../service/userApi.js";

export const useChatStore = defineStore('chat', {
    state: () => ({
        chatList: [],
        currentChatId: null,
        userId: null, // 初始化为 null
        indexContent: '😊 您好！我是您的贴心AI助手小颐，随时为您服务：\n' +
            '\n' +
            '1. **健康管理** 🩺：  \n' +
            '   - 身体不适别担心，告诉我症状，给您温暖建议（如“头晕怎么办”）。  \n' +
            '\n' +
            '2. **服务调度** 📅：  \n' +
            '   - 协助预约服务（如上门护理、养老院预约服务），轻松安排。  \n' +
            '\n' +
            '3. **政策咨询** 💼：  \n' +
            '   - 解答养老金、医保报销等疑问，清晰指引每一步。  \n' +
            '\n' +
            '**如何开始？**  \n' +
            '- 直接告诉我您的需求，比如：“我头晕怎么办”、“帮我预约护理服务”。  \n' +
            '\n' +
            '**温馨提示**：  \n' +
            '- 医疗建议仅供参考，请以医生面诊为准。  \n' +
            '\n' +
            '😊 有什么需要，随时告诉我！\n',
    }),
    actions: {
        async fetchUserId() {
            const res = await getLoginerInfo();
            this.userId = 'user_' + res.data.id; // 更新 userId
        },
        loadChatList() {
            const saved = localStorage.getItem('chatList');
            if (saved) this.chatList = JSON.parse(saved);
            this.fetchUserId(); // 在加载聊天列表时获取用户 ID
        },
        saveChatList() {
            localStorage.setItem('chatList', JSON.stringify(this.chatList));
        },
        addChat() {
            const newChat = {
                id: Date.now().toString(),
                title: `对话 ${this.chatList.length + 1}`,
                messages: [],
            };
            this.chatList.push(newChat);
            this.saveChatList();
            // 添加初始消息
            this.appendMessageToChat(newChat.id, 'assistant', this.indexContent, true);
            return newChat.id;
        },
        selectChat(chatId) {
            this.currentChatId = chatId;
        },
        appendMessageToCurrent(type, content, isComplete = false) {
            const chat = this.chatList.find(c => c.id === this.currentChatId);
            if (chat) {
                chat.messages.push({
                    role: type,
                    content,
                    timestamp: new Date().toLocaleTimeString(),
                    isMarkdown: type === 'assistant',
                    typing: !isComplete && type === 'assistant',
                    placement: type === 'user' ? 'end' : 'start', // 确保 placement 正确
                });
                this.saveChatList();
            }
        },
        appendMessageToChat(chatId, type, content, isComplete = false) {
            const chat = this.chatList.find(c => c.id === chatId);
            if (chat) {
                chat.messages.push({
                    role: type,
                    content,
                    timestamp: new Date().toLocaleTimeString(),
                    isMarkdown: type === 'assistant',
                    typing: !isComplete && type === 'assistant',
                    placement: type === 'user' ? 'end' : 'start',
                });
                this.saveChatList();
            }
        },
        updateCurrentBotMessage(content) {
            const chat = this.chatList.find(c => c.id === this.currentChatId);
            if (chat && chat.messages.length > 0) {
                const lastMessage = chat.messages[chat.messages.length - 1];
                if (lastMessage.role === 'assistant' && lastMessage.typing) {
                    lastMessage.content += content;
                }
                this.saveChatList();
            }
        },
        completeCurrentBotMessage() {
            const chat = this.chatList.find(c => c.id === this.currentChatId);
            if (chat && chat.messages.length > 0) {
                const lastMessage = chat.messages[chat.messages.length - 1];
                if (lastMessage.role === 'assistant' && lastMessage.typing) {
                    lastMessage.typing = false;
                }
                this.saveChatList();
            }
        },
        getCurrentMessages() {
            const chat = this.chatList.find(c => c.id === this.currentChatId);
            return chat ? chat.messages : [];
        },
        pinChat(chatId) {
            const index = this.chatList.findIndex(c => c.id === chatId);
            if (index > 0) {
                const [chat] = this.chatList.splice(index, 1);
                this.chatList.unshift(chat);
                this.saveChatList();
            }
        },
        deleteChat(chatId) {
            this.chatList = this.chatList.filter(c => c.id !== chatId);
            this.saveChatList();
        },
        // 新增方法：删除当前会话的最后一条消息
        removeLastMessage() {
            const chat = this.chatList.find(c => c.id === this.currentChatId);
            if (chat && chat.messages.length > 0) {
                chat.messages.pop(); // 移除最后一条消息
                this.saveChatList();
            }
        },
    },
});